<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true"  label-width="100px">
      <el-form-item label="场站名称" prop="stationCode">
        <el-select v-model="queryParams.stationCode" placeholder="请选择场站" clearable>
          <el-option v-for="station in stationList" :key="station.chargeStationCode" :label="station.chargeStationName" :value="station.chargeStationCode" />
        </el-select>
      </el-form-item>
      <el-form-item label="计费模版" prop="modelId">
        <el-select v-model="queryParams.modelId" placeholder="请选择场站" clearable>
          <el-option v-for="model in modelList" :key="model.priceTypeId" :label="model.priceTypeName" :value="model.priceTypeId" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['operator:tactics:add']">新增</el-button>
      </el-col>
    </el-row>

    <el-table :data="tacticsList">
      <el-table-column label="序号" type="index" width="50" align="center"/>
      <el-table-column label="策略名称" align="center" prop="tacticsName" />
      <el-table-column label="场站名称" align="center" prop="stationName" />
      <el-table-column label="计费模版" align="center" prop="modelName" />
      <el-table-column label="生效时间" align="center" prop="startTime" />
      <el-table-column label="结束时间" align="center" prop="endTime" />
      <el-table-column label="电价" align="center" prop="price1" />
      <el-table-column label="服务费" align="center" prop="price2" />
      <el-table-column label="停车费" align="center" prop="price3" />
      <el-table-column label="默认策略" align="center" prop="isDefault" >
        <template slot-scope="scope">
          <span v-if="scope.row.isDefault === '0'" >否</span>
          <span v-if="scope.row.isDefault !== '0'" >是</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" >
        <template slot-scope="scope">
          <span v-if="scope.row.status === '0'" style="color: #5a5e66">停用</span>
          <span v-if="scope.row.status !== '0'" style="color: #13ce66">启用</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="160">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleDetails(scope.row)"
            v-hasPermi="['operator:tactics:info']"
          >详情
          </el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['operator:tactics:edit']"
          >修改
          </el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['operator:tactics:del']"
            :disabled="scope.row.isDefault === '1'"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getTacticsList" />

    <!-- 添加或修改策略-->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="auto">
        <el-form-item label="策略名称" prop="tacticsName">
          <el-input v-model="form.tacticsName" placeholder="请输入策略名称"/>
        </el-form-item>
        <el-form-item label="场站名称" prop="stationCode">
          <el-select style="width: 100%" v-model="form.stationCode" placeholder="请选择场站" @change="filterModelList">
            <el-option
              v-for="item in stationList"
              :key="item.chargeStationCode"
              :label="item.chargeStationName"
              :value="item.chargeStationCode">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="计费模版" prop="modelId">
          <el-select style="width: 100%" v-model="form.modelId" placeholder="请选择计费模版" @change="getPriceList">
            <el-option
              v-for="item in currModelList"
              :key="item.priceTypeId"
              :label="item.priceTypeName"
              :value="item.priceTypeId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-table v-if="priceList.length > 0" v-loading="loading" :data="priceList" height="200" style="margin-bottom: 20px">
          <el-table-column label="时间段" align="center">
            <template slot-scope="scope">{{scope.row.startTime + '-' + scope.row.endTime}}</template>
          </el-table-column>
          <el-table-column label="电价" align="center" width="100" prop="electricCharge" />
          <el-table-column label="服务费" align="center" width="100" prop="serviceFee" />
          <el-table-column label="停车费" align="center" width="100" prop="stopFee" />
        </el-table>
        <el-form-item label="生效时间" prop="dateArray">
          <el-date-picker
            style="width: 100%"
            v-model="form.dateArray"
            type="datetimerange"
            range-separator="-"
            start-placeholder="生效日期"
            end-placeholder="结束日期"/>
        </el-form-item>
        <el-form-item label="启用状态" prop="status">
          <el-switch
            v-model="form.status"
            active-value="1"
            inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :disabled="form.isDefault === '1'">
          </el-switch>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="open = false">取 消</el-button>
        </div>
    </el-dialog>

    <!-- 详情 -->
    <el-dialog :title="detailTitle" :visible.sync="detailOpen" width="50%" center append-to-body>
      <el-table v-loading="loading" :data="priceList">
        <el-table-column label="时间段" align="center">
          <template slot-scope="scope">{{scope.row.startTime + '-' + scope.row.endTime}}</template>
        </el-table-column>
        <el-table-column label="电价" align="center" prop="electricCharge" />
        <el-table-column label="服务费" align="center" prop="serviceFee" />
        <el-table-column label="停车费" align="center" prop="stopFee" />
      </el-table>
    </el-dialog>
  </div>

</template>

<script>
  import { listPrice } from "@/api/smart/operator/electricityPrice";
  import { listPriceType } from "@/api/smart/operator/priceType";
  import { listStation } from "@/api/smart/operator/station";
  import { getList, add, edit, remove, info } from "@/api/smart/operator/priceTactics";

    export default {
      name: "tactics",
      dicts: ['use_state','current_type'],
      data() {
        return {
          // 遮罩层
          loading: true,
          title: '',
          detailTitle: '时段详情',
          open: false,
          detailOpen: false,
          stationList: [],
          modelList: [],
          tacticsList: [],
          priceList: [],
          currModelList: [],
          // 总条数
          total: 0,
          // 查询参数
          queryParams: {
            pageNum: 1,
            pageSize: 10,
            portName: null,
            stationCode: null,
            serviceStatus: null
          },
          // 表单参数
          form: {
            stationCode: null,
          },
          // 表单校验
          rules: {
            tacticsName: [{ required: true, message: '策略名称不能为空', trigger: 'blur' }],
            stationCode: [{ required: true, message: '场站不能为空', trigger: 'blur' }],
            modelId: [{ required: true, message: '模版不能为空', trigger: 'blur' }],
            dateArray: [{ required: true, message: '生效时间不能为空', trigger: 'blur' }],
          },
        }
      },
      created() {
        this.getTacticsList();
        this.getStationAndDeviceList();
      },
      methods: {
        //获取策略列表
        getTacticsList(){
          this.loading = true;
          getList(this.queryParams).then(res=>{
            this.tacticsList = res.rows;
            this.total = res.total;
            this.loading = false;
          });
        },
        //提交按钮
        submitForm(){
          let param = this.form;
          const  priceCode=this.getPriceCode(param.modelId);
          param.priceTypeCode=priceCode;
          this.$refs["form"].validate(valid => {
            if(!valid) return;
            param.startTime = param.dateArray[0].toLocaleString();
            param.endTime = param.dateArray[1].toLocaleString();
            switch (this.form.$tag) {
              case "edit":
                edit(param).then(res=>{
                  this.$modal.msgSuccess("修改成功");
                  this.open = false;
                  this.getTacticsList();
                });
                break
              case "add":
                add(param).then(res=>{
                  this.$modal.msgSuccess("添加成功");
                  this.open = false;
                  this.getTacticsList();
                });
                break;
            }
          });
        },
        //详情按钮操作
        handleDetails(row){
          this.detailOpen = true;
          this.getPriceList(row.modelId);
        },
        //新增操作
        handleAdd(){
          this.form = {};
          this.form.$tag = 'add';
          this.priceList = [];
          this.title = "添加策略";
          this.open = true;
        },
        //修改操作
        handleUpdate(row) {
          info(row.id).then(res=>{
            this.form = res.data;
            this.filterModelList(this.form.stationCode);
            this.form.dateArray = [new Date(this.form.startTime), new Date(this.form.endTime)]
            this.form.$tag = 'edit';
            this.title = "修改策略";
            this.open = true;
            if(row){
              this.getPriceList(row.modelId);
            }
          });
        },
        //删除操作
        handleDelete(row){
          const tacticsName = row.tacticsName;
          this.$modal.confirm('是否确认删除名称为"' + tacticsName + '"的数据项？').then(function() {
            return remove(row.id);
          }).then(() => {
            //this.init();
            this.handleQuery();
            this.$modal.msgSuccess("删除成功");
          }).catch(() => {});
        },
        /** 搜索按钮操作 */
        handleQuery() {
          this.queryParams.pageNum = 1;
          this.getTacticsList();
        },
        /** 重置按钮操作 */
        resetQuery() {
          this.resetForm('queryForm');
          this.handleQuery();
        },
        /** 查询场站和模版列表 */
        async getStationAndDeviceList() {
          this.loading = true;
          await listStation(this.queryParams).then(response => {
            this.stationList = response.rows;
          });
          await listPriceType({pageNum: 1,pageSize: 100}).then(res=>{
            this.modelList = res.rows;
          });
          this.loading = false;
        },
        /** 查询场站电区间价设置列表 */
        getPriceList(modelId) {
          console.log(modelId, 'row');
          this.loading = true;
          listPrice({priceTypeId: modelId, pageNum: 1, pageSize: 100}).then(response => {
            this.priceList = response.rows;
            this.loading = false;
          });
        },
        //过滤模版
        filterModelList(stationCode){
          this.currModelList = this.modelList.filter(e=>{return e.chargeStationCode === stationCode});
          },
        //获取计费模版编码
        getPriceCode(selectedValue){
          const selectedPrice = this.modelList.find(price => price.priceTypeId === selectedValue);
          return selectedPrice ? selectedPrice.priceTypeCode : '';
        },
      }
    }
</script>

<style lang="scss" scoped>
  .topNum {
    margin: 20px 0;
    h4{
      font-size: 14px;
      color: #8D8D8D;
      margin: 0 !important;
    }
    p{
      font-size: 23px;
      margin: 10px 0 0 !important;
    }
    .topText{
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
    }
    .topBorder{
      border-right: 1px solid #F1F1F1;
    }
  }
</style>
